//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "MemberViewController.h"
#import "LoginViewController.h"
#import "Config.h"
#import "SBJson.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "MemberSettingsController.h"
#import "MemberFavoriteLisViewController.h"
#import "HomeViewController.h"
#import "CommentsViewController.h"
#import "CommentsInfoViewController.h"
#import "OrderListViewController.h"
#import "OMGToast.h"
#import "LatestViewController.h"
#import "MyUploadViewController.h"
#import "MyCardListViewController.h"
#import "MyTicketViewController.h"
#import "AppDelegate.h"
@interface MemberViewController ()

@end

@implementation MemberViewController
@synthesize lbTitle;
static int type;
UIAlertView *alert;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    _view1.layer.masksToBounds=YES;
    [_view1.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_view1.layer setBorderWidth:0.5f];
    [_view1.layer setCornerRadius:10];
     _view2.layer.masksToBounds=YES;
    [_view2.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_view2.layer setBorderWidth:0.5f];
    [_view2.layer setCornerRadius:10];
     _view3.layer.masksToBounds=YES;
    [_view3.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_view3.layer setBorderWidth:0.5f];
    [_view3.layer setCornerRadius:10];
     _view4.layer.masksToBounds=YES;
    [_view4.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_view4.layer setBorderWidth:0.5f];
    [_view4.layer setCornerRadius:10];
    _view5.layer.masksToBounds=YES;
    [_view5.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_view5.layer setBorderWidth:0.5f];
    [_view5.layer setCornerRadius:10];
    _view6.layer.masksToBounds=YES;
    [_view6.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [_view6.layer setBorderWidth:0.5f];
    [_view6.layer setCornerRadius:10];
    strHeaderImage=nil;
    _imageNotice.hidden=YES;
}
- (void)viewWillAppear:(BOOL)animated
{
    [self hasLogin];
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(delegate.bNotice)
    {
        _imageNotice.hidden=NO;
    }
    else
    {
        _imageNotice.hidden=YES;
    }
}
- (void)hasLogin
{
    int memberId = [[Config Instance] getMemberId];
    if(memberId == 0)
    {
        LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        //    view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
    }else
    {
        type=2;
        int memberId=[[Config Instance]getMemberId];
        NSString *sid=[NSString stringWithFormat:@"%d",memberId];
        NSString *pwd=[[Config Instance]getPassword];
        NSURL *url=[NSURL URLWithString:url_memberNumber];
        ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
        [request setPostValue:sid forKey:@"member.memberID"];
        [request setPostValue:pwd forKey:@"member.password"];
        [request setShouldAttemptPersistentConnection:NO];
        [request setDidFinishSelector:@selector(finishPointBalance:)];
        [request setDelegate:self];
        [request startAsynchronous];
        NSString *strImage=[[Config Instance] getImageUrl];
        if(strImage.length>0)
        {
            NSString *strImg=[[strImage stringByReplacingOccurrencesOfString:@":" withString:@""] stringByReplacingOccurrencesOfString:@"/" withString:@""];
            NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:strImg]];
            if (![[NSFileManager defaultManager] fileExistsAtPath:imageDataPath]) {
                
                NSURL *imageUrl = [NSURL URLWithString:[strImage stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
                NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
                [imageData writeToFile:imageDataPath atomically:YES];
                UIImage *image = [UIImage imageWithData:imageData];
                if(image)
                {
                    [_ImageView setImage:image];
                    strHeaderImage=imageDataPath;
                }
                else
                {
                    _ImageView.image=[UIImage imageNamed:@"huang@2x.png"];
                    strHeaderImage=nil;
                }
            }
            else
            {
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
                [_ImageView setImage:image];
                strHeaderImage=imageDataPath;
            }
            
        }
        else
        {
            strHeaderImage=nil;
            _ImageView.image=[UIImage imageNamed:@"huang@2x.png"];
        }
        NSString * nickName = [[Config Instance] getNickName];
        if(nickName.length>0)
        {
        //if([nickName isEqualToString:@"" ]==NO||[nickName isEqual:nil]==NO)//modify by xj 修改昵称为空的时候，用户管理界面显示会员手机号码
            _lbName.text = [NSString stringWithFormat:@"%@",nickName];
        }
        lbTitle.text = [NSString stringWithFormat:@"%@",[[Config Instance] getMobile]];
        if ([[Config Instance]getPayPassword] == NULL) {
            [OMGToast showWithText:MSG_NEED_PAYPASSWORD bottomOffset:100];
        }
    }
}
- (void)viewDidUnload
{
    [self setLbTitle:nil];
    [self setView1:nil];
    [self setView2:nil];
    [self setView3:nil];
    [self setView4:nil];
    [self setImageView:nil];
    [self setLbPoint:nil];
    [self setLbRemark:nil];
    [self setLbFav:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"我的惠订";
    }
    return self;
}
- (IBAction)accountSetting:(id)sender {
    MemberSettingsController  *view = [[MemberSettingsController alloc] initWithNibName:@"MemberSettingsController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    view.strHeaderImage=strHeaderImage;
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)loginOut:(id)sender {
    UIAlertView *loginOutview=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"退出登录?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"退出", nil];
    [loginOutview show];
}
- (IBAction)ShowMyTicket:(id)sender {
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(delegate.bNotice)
    {
        _imageNotice.hidden=YES;
        delegate.bNotice=NO;
    }
    MyTicketViewController* view=[[MyTicketViewController alloc] initWithNibName:@"MyTicketViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)showMyCard:(id)sender {
    MyCardListViewController* view=[[MyCardListViewController alloc] initWithNibName:@"MyCardListViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{
    if (buttonIndex == 1)
    {
        int memberid=[[Config Instance] getMemberId];
        NSString *stringInt = [NSString stringWithFormat:@"%d",memberid];
        NSURL *url=[NSURL URLWithString:url_loginout];
        ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
        [request setPostValue: stringInt forKey:@"member.memberID"];
        [request setDelegate: self];
        [request startAsynchronous];
        LoginViewController *view=[[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        //view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        [[Config Instance] setMemberId:0];
    }else{
        return;
    }
    
}


- (IBAction)favoriteList:(id)sender {
    MemberFavoriteLisViewController *view=[[MemberFavoriteLisViewController alloc]initWithNibName:@"MemberFavoriteLisViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
	[self.navigationController pushViewController:view animated:YES];
}

- (IBAction)pointBalance:(id)sender {
    type=1;
    int memberId=[[Config Instance]getMemberId];
    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
    NSString *pwd=[[Config Instance]getPassword];
    NSURL *url=[NSURL URLWithString:url_pointBalance];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:sid forKey:@"member.memberID"];
    [request setPostValue:pwd forKey:@"member.password"];
    [request setShouldAttemptPersistentConnection:NO];
    [request setDidFinishSelector:@selector(finishPointBalance:)];
    [request setDelegate:self];
    [request startAsynchronous];
}


- (IBAction)getCommentsInfo:(id)sender {
    CommentsInfoViewController *view=[[CommentsInfoViewController alloc]initWithNibName:@"CommentsInfoViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)myOrder:(id)sender {
    OrderListViewController *view=[[OrderListViewController alloc]initWithNibName:@"OrderListViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (IBAction)OnMyUpdate:(id)sender {
    MyUploadViewController *view=[[MyUploadViewController alloc] initWithNibName:@"MyUploadViewController" bundle:nil];
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:YES];
}

- (void)finishPointBalance:(ASIHTTPRequest *)request
{
    if(type==1){
        NSString *jsonStr = [request responseString];
        //NSLog(@"%@",jsonStr);
        NSDictionary *dic = [jsonStr JSONValue];
        if(![[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"]){
            UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:[dic valueForKey:@"log"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [view show];
            return;
        }
        NSDictionary *data= [dic valueForKey:@"data"];
        int point=[[data valueForKey:@"point"] intValue];
        double money=[[data valueForKey:@"money"]doubleValue];
        NSString *mesg=[NSString stringWithFormat:@"您的积分为:%d\n现金为:%8.2f元",point,money];
        alert=[[UIAlertView alloc]initWithTitle:@"积分余额"
                                        message:mesg
                                       delegate:nil
                              cancelButtonTitle:nil
                              otherButtonTitles:nil];
        [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector: @selector(performDismiss:)
                                       userInfo:nil repeats:NO];
        [alert show];
    }
    else if (type==2)
    {
        NSString *jsonStr = [request responseString];
        //NSLog(@"%@",jsonStr);
        NSDictionary *dic = [jsonStr JSONValue];
        if([dic valueForKey:@"log"]!=[NSNull null] && [[dic valueForKey:@"log"] compare:@"登录已经过期，请重新登录" options:1]==NSOrderedSame)
        {
            LoginViewController  *view = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
            //    view.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:view animated:YES];
            return;
        }
        NSDictionary *data= [dic valueForKey:@"data"];
        _lbPoint.text=[NSString stringWithFormat:@"%d",[[data valueForKey:@"POINT"] intValue]];
        _lbRemark.text=[NSString stringWithFormat:@"%d",[[data valueForKey:@"REMARK"] intValue]];
        _lbFav.text=[NSString stringWithFormat:@"%d",[[data valueForKey:@"FAVORITE"] intValue]];
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
}
- (void) performDismiss: (NSTimer *)timer
{
    [alert dismissWithClickedButtonIndex:0 animated:NO];
}

@end
